﻿///////////////////////////////////////////////////////////////////////////////
//	Copyright 2013 JASDev International
//
//	Licensed under the Apache License, Version 2.0 (the "License");
//	you may not use this file except in compliance with the License.
//	You may obtain a copy of the License at
//
//		http://www.apache.org/licenses/LICENSE-2.0
//
//	Unless required by applicable law or agreed to in writing, software
//	distributed under the License is distributed on an "AS IS" BASIS,
//	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//	See the License for the specific language governing permissions and
//	limitations under the License.
///////////////////////////////////////////////////////////////////////////////

using System;
using System.Text;

namespace JDI.Common.Extensions
{
	public static class UriExtensions
	{
		// TODO - test these extensions

		/// <summary>
		/// Path
		/// </summary>
		/// <remarks>
		/// Based on RFC3986 Generic Syntax
		///	  authority = //[userinfo@]host[:port]
		///	  scheme:[authority][/path]["?" query]
		///	  http:[//[username:password@]www.test.com[:80]][/folder/file][?a=b&c=d]
		/// </remarks>
		public static string GetPath(this Uri uri)
		{
			int posAuth = uri.AbsoluteUri.IndexOf("//");
			int posPath = (posAuth >= 0 ? uri.AbsoluteUri.IndexOf('/', posAuth + 2) : uri.AbsoluteUri.IndexOf('/'));
			int posQuery = uri.AbsoluteUri.IndexOf('?');
			int lenUri = uri.AbsoluteUri.Length;
			int lenPath = (posPath >= 0 ? (posQuery >= 0 ? posQuery - posPath : lenUri - posPath) : 0);

			return (lenPath > 0 ? uri.AbsoluteUri.Substring(posPath, lenPath) : "/");
		}

		public static string GetQuery(this Uri uri)
		{
			int posAuth = uri.AbsoluteUri.IndexOf("//");
			int posPath = (posAuth >= 0 ? uri.AbsoluteUri.IndexOf('/', posAuth + 2) : uri.AbsoluteUri.IndexOf('/'));
			int posQuery = uri.AbsoluteUri.IndexOf('?');
			int lenUri = uri.AbsoluteUri.Length;
			int lenPath = (posPath >= 0 ? (posQuery >= 0 ? posQuery - posPath : lenUri - posPath) : 0);

			return (posQuery >= 0 ? uri.AbsoluteUri.Substring(posQuery) : "");
		}

		public static string GetPathAndQuery(this Uri uri)
		{
			int posAuth = uri.AbsoluteUri.IndexOf("//");
			int posPath = (posAuth >= 0 ? uri.AbsoluteUri.IndexOf('/', posAuth + 2) : uri.AbsoluteUri.IndexOf('/'));
			int posQuery = uri.AbsoluteUri.IndexOf('?');
			int lenUri = uri.AbsoluteUri.Length;
			int lenPath = (posPath >= 0 ? (posQuery >= 0 ? posQuery - posPath : lenUri - posPath) : 0);

			string path = (lenPath > 0 ? uri.AbsoluteUri.Substring(posPath, lenPath) : "/");
			return string.Concat(path, (posQuery >= 0 ? uri.AbsoluteUri.Substring(posQuery) : ""));
		}
	}
}
